const joi = require('joi');
const dbQuery = require('../model/db');
const bcryptjs = require('bcryptjs');
const {
	sendError,
	sendSuccess
} = require('../utils/sendFunction');

// 验证规则
// id password(4-12) nickname(1-10) sex  introduction avator 
const schemaEditUserInfo = joi.object({
	password: joi.string().min(4).max(12).required().error(new Error('password不符合验证规则')),
	nickname: joi.string().min(1).max(10).required().error(new Error('nickname不符合验证规则')),
	sex: joi.string().required().error(new Error('sex不符合验证规则')),
	id: joi.number().required().error(new Error('id不符合验证规则')),
})

// id nickname(1-10) sex  introduction avator 
const schemaEditUserInfoNoPassword = joi.object({
	nickname: joi.string().min(1).max(10).required().error(new Error('nickname不符合验证规则')),
	sex: joi.string().required().error(new Error('sex不符合验证规则')),
	id: joi.number().required().error(new Error('id不符合验证规则')),
})

const schemaGetUserInfoAndDelete = joi.object({
	id: joi.number().required().error(new Error('id不符合验证规则'))
})

const getUserList = async function (req, res, next) {
	let sqlStr = 'select userid,username,user_nickname,user_sex,user_avator_url,user_create_time,user_introduction from user';
	let result = await dbQuery(sqlStr);
	if (result.length >= 0) {
		sendSuccess(res, '获取用户列表成功!', {
			data: result
		})
	} else {
		sendError(res, 500, '获取用户列表失败，请稍后再试!')
	}
}

const getAdminList = async function (req, res, next) {
	let sqlStr = 'select username,adminid from admin';
	let result = await dbQuery(sqlStr);
	if (result.length >= 0) {
		sendSuccess(res, '获取管理员列表成功!', {
			data: result
		})
	} else {
		sendError(res, 500, '获取管理员列表失败，请稍后再试!')
	}
}

// id
const getUserInfo = async function (req, res, next) {
	let {
		id
	} = req.query;

	if (!id) {
		sendError(res, 200, 'id不能为空!');
		return;
	}

	try {
		await schemaGetUserInfoAndDelete.validateAsync({
			id
		})
	} catch (error) {
		next(error)
		return
	}

	let sqlStr = 'select userid,username,user_nickname,user_sex,user_avator_url,user_create_time,user_introduction from user where userid=?'
	let result = await dbQuery(sqlStr, [id]);
	if (result.length == 1) {
		sendSuccess(res, '获取用户信息成功!', {
			data: result
		});
	} else {
		sendError(res, 500, '获取用户信息失败，请稍后再试!')
	}
}

// id password(4-12) nickname(1-10) sex  introduction avator 
const editUserInfo = async function (req, res, next) {
	let info = req.body;

	if (!info.nickname || !info.id || !info.sex) {
		sendError(res, 200, '用户昵称或用户性别或id不能为空!');
		return;
	}

	if (info.password) {
		try {
			await schemaEditUserInfo.validateAsync({
				password: info.password,
				nickname: info.nickname,
				sex: info.sex,
				id: info.id
			})
		} catch (error) {
			next(error);
			return;
		}
		// 密码加密
		var salt = await bcryptjs.genSalt(10);
		var hashPassword = await bcryptjs.hash(info.password, salt);
	} else {
		try {
			await schemaEditUserInfoNoPassword.validateAsync({
				nickname: info.nickname,
				sex: info.sex,
				id: info.id
			})
		} catch (error) {
			next(error);
			return;
		}
	}

	let sqlStr = 'select * from user where user_nickname=? and userid!=?'
	let result = await dbQuery(sqlStr, [info.nickname, info.id]);
	if (result.length !== 0) {
		sendError(res, 200, '用户昵称被占用，请更换其他用户昵称!');
		return;
	}

	if (req.file) {
		var avator = req.file.path.split('server\\')[1].replace('\\', '/').replace('\\', '/');
	}

	var sqlStr1;
	var result1;
	if (req.file && !info.password) {
		sqlStr1 = 'update user set user_nickname=?,user_sex=?,user_avator_url=?,user_introduction=? where userid=?';
		result1 = await dbQuery(sqlStr1, [info.nickname, info.sex, avator, info.introduction, info.id]);
	} else if (!req.file && info.password) {
		sqlStr1 = 'update user set password=?,user_nickname=?,user_sex=?,user_introduction=? where userid=?';
		result1 = await dbQuery(sqlStr1, [hashPassword, info.nickname, info.sex, info.introduction, info.id]);
	} else if (info.password && req.file) {
		sqlStr1 = 'update user set password=?,user_nickname=?,user_sex=?,user_avator_url=?,user_introduction=? where userid=?';
		result1 = await dbQuery(sqlStr1, [hashPassword, info.nickname, info.sex, avator, info.introduction, info.id]);
	} else if (!info.password && !req.file) {
		sqlStr1 = 'update user set user_nickname=?,user_sex=?,user_introduction=? where userid=?';
		result1 = await dbQuery(sqlStr1, [info.nickname, info.sex, info.introduction, info.id]);
	}

	if (result1.affectedRows == 1) {
		sendSuccess(res, '修改用户信息成功!');
	} else {
		sendError(res, 500, '修改用户信息失败，请稍后再试!')
	}
}

const deleteUser = async function (req, res, next) {
	let {
		id
	} = req.query;

	if (!id) {
		sendError(res, 200, 'id不能为空!');
		return;
	}

	try {
		await schemaGetUserInfoAndDelete.validateAsync({
			id
		})
	} catch (error) {
		next(error);
		return;
	}

	// 级联删除
	let sqlStr = 'delete from user where userid=?';
	let result = await dbQuery(sqlStr, [id]);
	let sqlStr1 = 'delete from collect where user_id=?';
	let result1 = await dbQuery(sqlStr1, [id]);
	let sqlStr2 = 'delete from gedan where gedan_user_id=?';
	let result2 = await dbQuery(sqlStr2, [id]);
	let sqlStr3 = 'delete from comment where user_id=?';
	let result3 = await dbQuery(sqlStr3, [id]);

	if (result.affectedRows == 1 && result2.affectedRows >= 0 && result3.affectedRows >= 0 && result1.affectedRows >= 0) {
		sendSuccess(res, '删除用户成功!');
	} else {
		sendError(res, 500, '删除用户失败，请稍后再试!')
	}
}

const deleteAdmin = async function (req, res, next) {
	let {
		id
	} = req.query;

	if (!id) {
		sendError(res, 200, 'id不能为空!');
		return;
	}

	try {
		await schemaGetUserInfoAndDelete.validateAsync({
			id
		})
	} catch (error) {
		next(error);
		return;
	}

	let sqlStr = 'select * from admin where adminid=?';
	let result = await dbQuery(sqlStr, [id]);
	if (result[0].username == 'admin') {
		sendError(res, 200, '删除管理员失败，你不能删除该管理员!')
		return;
	}


	let sqlStr1 = 'delete from admin where adminid=?'
	let result1 = await dbQuery(sqlStr1, [id]);
	if (result1.affectedRows == 1) {
		sendSuccess(res, '删除管理员成功!');
	} else {
		sendError(res, 500, '删除管理员失败，请稍后再试!')
	}
}


module.exports = {
	getUserList,
	getAdminList,
	editUserInfo,
	getUserInfo,
	deleteUser,
	deleteAdmin
}